package edu.gznu.ics.fast.pulsar.service.prestoacc.picService.impl;

import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import edu.gznu.ics.fast.pulsar.model.vo.prestoacc.task.computeTask.TaskMonitorItemVO;
import edu.gznu.ics.fast.pulsar.service.prestoacc.picService.TaskMonitorService;

@Service("taskMonitorService")
public class TaskMonitorServiceImpl implements TaskMonitorService {
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Override
	public List<TaskMonitorItemVO> findList() {
		String sql = "select t.file_id, t.file_name, p.task_id, "
				+ "p.startdt, p.enddt, p.ip, p.distrubted, p.calover "
				+ "from t_fits_info t "
				+ "left join t_task p "
				+ "on t.file_id = p.file_id "
				+ "left join ( "
				+ "select t.file_id, t.task_id from t_pic_info t group by t.file_id, t.task_id"
				+ ") q "
				+ "on p.file_id = q.file_id and p.task_id = q.task_id "
				+ "where (p.calover = 0) "
				+ "or (p.calover = 1 and q.file_id is not null) "
				+ "order by p.calover desc, p.distrubted desc ";
		List<TaskMonitorItemVO> itemList = new LinkedList<TaskMonitorItemVO>();
		List<Map<String, Object>> results = jdbcTemplate.queryForList(sql);
		for(int i = 0; i < results.size(); i++) {
			Map<String, Object> row = results.get(i);
			TaskMonitorItemVO vo = new TaskMonitorItemVO();
			vo.setNumber(i + 1);
			vo.setFileId(((BigDecimal) row.get("FILE_ID")).intValue());
			vo.setFileName((String) row.get("FILE_NAME"));
			vo.setTaskId(((BigDecimal) row.get("TASK_ID")).intValue());
			vo.setIp((String) row.get("IP"));
			vo.setStartTime((String) row.get("STARTDT"));
			vo.setEndTime((String) row.get("ENDDT"));
			int distrubted = ((BigDecimal) row.get("DISTRUBTED")).byteValue();
			int calover = ((BigDecimal) row.get("CALOVER")).byteValue();
			if(distrubted == 0) {
				vo.setStatus("UNSTART");
			} else {
				if(calover == 0) {
					if(vo.getStartTime() == null) {
						vo.setStatus("QUEUE");
					} else {
						vo.setStatus("PROCESSING");
					}
				} else {
					vo.setStatus("COMPLETE");
				}
			}
			itemList.add(vo);
		}
		return itemList;
	}
}
